#coding:utf-8
import psutil,time
def bytes2human(n):
    '字节转换为其他单位返回为str'
    symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
    prefix = {}
    for i, s in enumerate(symbols):
        prefix[s] = 1 << (i + 1) * 10
    for s in reversed(symbols):
        if n >= prefix[s]:
            value = float(n) / prefix[s]
            return '%.2f %s' % (value, s)
    return '%.2f B' % (n)

def getServerInfo():
    mem = psutil.virtual_memory().percent
    cpu = psutil.cpu_percent(interval=1)
    tot_before = psutil.net_io_counters()
    time.sleep(1)
    tot_after = psutil.net_io_counters()
    uploadSpeed = bytes2human(tot_after.bytes_sent - tot_before.bytes_sent)
    downloadSpeed = bytes2human(tot_after.bytes_recv - tot_before.bytes_recv)
    return {
        'mem':mem,
        'cpu':cpu,
        'up':uploadSpeed,
        'down':downloadSpeed
    }